import 'babel-polyfill';
import Koa from 'koa2';
import bodyParser from 'koa-bodyparser';
import koaLogger from 'koa-logger';
import mount from 'koa-mount';
import staticCache from 'koa-static-cache';
import convert from 'koa-convert';
import json from 'koa-json';
import path from 'path';
import router from './routes';
import views from 'koa-views';
import fs from 'fs';
import session from 'koa-session2';
import helmet from 'koa-helmet';
import cluster from 'cluster';
import os from 'os';
import routerHandle from './middlewares/routerHandle';
import checkLogin from './middlewares/checkLogin';
import queryHandle from './middlewares/queryHandle';

let numCpus = os.cpus().length;
const app = new Koa();

// 一些默认的安全设置
app.use(helmet());

app.use(session({
    key: 'xone',
    maxAge: 24 * 60 * 60 * 1000,
    path: '/',
}));
// 预先设置query，用来记录客户端请求的query
app.use(async (ctx, next) => {
    if (!ctx.session.query) {
        ctx.session.query = {};
    }
    await next();
});
// 设置后端视图目录及模板引擎
app.use(views(path.join(__dirname, '../dist/server/views'), {
    map: {html: 'nunjucks'},
}));

// 设置静态目录
app.use(staticCache(path.join(__dirname, '../dist/web'), {
    maxAge: 24 * 60 * 60,
}));

// 日志中间件
app.use(koaLogger());
app.use(bodyParser({
    enableTypes: ['json', 'form', 'text'],
}));
app.use(json());

// 检查是否登录
app.use(checkLogin);
app.use(queryHandle);
app.use(router.routes());
app.use(routerHandle);
app.use(router.allowedMethods());
if (cluster.isMaster) {
    for (let i = 0; i < numCpus; i++) {
        cluster.fork();
    }
    cluster.on('exit', function (worker, code, signal) {
        console.log('worker' + worker.process.pid + ' died');
    });
} else {
    app.listen(8080);
}
